package com.htjc.integral.redpacket.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.sql.Timestamp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.htjc.integral.common.util.HttpsClientTools;
import com.htjc.integral.common.util.UUIDUtil;
import com.htjc.integral.model.redpacket.BpRedPacInv;
import com.htjc.integral.redpacket.mapper.BpBuyRedPacketMapper;
import com.htjc.integral.redpacket.mapper.EcBpRedPacInvMapper;
import com.htjc.integral.redpacket.mapper.EcBpRedPacReqLogMapper;
import com.htjc.integral.redpacket.util.HtjcSignToolManageK;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic="redpacketLogger")
@Service
public class RedPacketForExtSysService {

	@Autowired
	private EcBpRedPacInvMapper ecbpRedPacInvMapper;
	
	@Autowired
	private BpBuyRedPacketMapper bpBuyRedPacketMapper;

	@Autowired
	private EcBpRedPacReqLogMapper ecBpRedPacReqLogMapper;

	@Autowired
	private HtjcSignToolManageK htjcSignToolManageK;
	/**
	 * 
	 * @商城派发电e宝红包接口（供外部系统使用）
	 * 
	 * @param celephoneNo：手机号码
	 * 			  dealId ：交易号（外部系统生成）
	 * 		   platformId：外部系统平台ID(商城生成， 提供给外部平台)
	 *         stockNumberId : 红包库存ID(参见EC_BP_RED_PAC_INV表id字段)
	 * 			
	 * 				  
	 * @return
	 */
	public String assignRedPacket(String params) {
		JSONObject result = new JSONObject();
		log.info("[外部系统派发红包接口开始]：" + params);

		Integer reqLogId = -1;// 商城生成的请求记录id

		String dealId = "";//外部平台传入的交易号

		String celephoneNo = "";//电话号码

		// 校验参数是否为空
		if (params == null || "".equals(params.trim())) {
			result.put("isSuccess", "0");
			result.put("errorMsg", "参数为空");
			result.put("dealId", dealId);
			result.put("handleID", reqLogId);
			result.put("responseCode", "0004");
			log.info("[外部系统派发红包接口end]:"+result.toString());
			return result.toString();
		}

		// 校验参数是否能够转换为json
		JSONObject paramJson = null;
		try {
			paramJson = JSON.parseObject(params);
		} catch (Exception e) {
			result.put("isSuccess", "0");
			result.put("errorMsg", "参数格式异常");
			result.put("dealId", dealId);
			result.put("handleID", reqLogId);
			result.put("responseCode", "1000");
			log.info("[外部系统派发红包接口end]:"+result.toString());
			return result.toString();
		}

		// 校验平台编号
		String platformId = "";
		try {
			platformId = paramJson.getString("platformId");
			if (platformId == null || "".equals(platformId.trim())) {
				result.put("isSuccess", "0");
				result.put("errorMsg", "平台编号为空");
				result.put("dealId", dealId);
				result.put("handleID", reqLogId);
				result.put("responseCode", "0004");
				log.info("[外部系统派发红包接口end]:"+result.toString());
				return result.toString();
			}

			Map<String, Object> getExtSysParaMap = new HashMap<String, Object>();
			getExtSysParaMap.put("ext_sys_id", platformId);
			List<Map<String, Object>> datas = this.ecbpRedPacInvMapper.getExtSys(getExtSysParaMap);
			if (datas == null || datas.isEmpty()) {
				result.put("isSuccess", "0");
				result.put("errorMsg", platformId + "非合作商平台编号");
				result.put("dealId", dealId);
				result.put("handleID", reqLogId);
				result.put("responseCode", "0001");
				log.info("[外部系统派发红包接口end]:"+result.toString());
				return result.toString();
			}

		} catch (Exception e) {
			result.put("isSuccess", "0");
			result.put("errorMsg", "校验平台ID异常");
			result.put("dealId", dealId);
			result.put("handleID", reqLogId);
			result.put("responseCode", "1000");
			log.info("[外部系统派发红包接口end]:"+result.toString());
			return result.toString();
		}

		// 校验手机号
		try {

			celephoneNo = paramJson.getString("celephoneNo");
			if (celephoneNo == null || "".equals(celephoneNo.trim())) {
				result.put("isSuccess", "0");
				result.put("errorMsg", "手机号为空");
				result.put("dealId", dealId);
				result.put("handleID", reqLogId);
				result.put("responseCode", "0004");
				log.info("[外部系统派发红包接口end]:"+result.toString());
				return result.toString();
			}

//			EcPartner user = this.ecPartnerMapper.selectUserByMobile(celephoneNo);
//			if (user == null) {
//				result.put("isSuccess", "0");
//				result.put("errorMsg", "非商城认证用户" + celephoneNo);
//				result.put("dealId", dealId);
//				result.put("handleID", reqLogId);
//				result.put("responseCode", "0003");
//				log.info("[外部系统派发红包接口end]:"+result.toString());
//				return result.toString();
//			}

		} catch (Exception e) {
			result.put("isSuccess", "0");
			result.put("errorMsg", "校验手机号码异常");
			result.put("dealId", dealId);
			result.put("handleID", reqLogId);
			result.put("responseCode", "1000");
			log.info("[外部系统派发红包接口end]:"+result.toString());
			return result.toString();
		}

		// 校验库存信息异常
		String stockNumberId = paramJson.getString("stockNumberId");
		String depotCode = "";
		try {

			if (stockNumberId == null || "".equals(stockNumberId.trim())) {
				result.put("isSuccess", "0");
				result.put("errorMsg", "面额编号为空");
				result.put("dealId", dealId);
				result.put("handleID", reqLogId);
				result.put("responseCode", "0004");
				log.info("[外部系统派发红包接口end]:"+result.toString());
				return result.toString();
			}

			Map<String, Object> getRedPacInvParams = new HashMap<String, Object>();
			getRedPacInvParams.put("id", stockNumberId);
			List<Map<String, Object>> pacInvs = this.ecbpRedPacInvMapper.getRedPacInv(getRedPacInvParams);
			if (pacInvs == null || pacInvs.isEmpty()) {
				result.put("isSuccess", "0");
				result.put("errorMsg", "不存的的红包库存" + stockNumberId);
				result.put("dealId", dealId);
				result.put("handleID", reqLogId);
				result.put("responseCode", "0004");
				log.info("[外部系统派发红包接口end]:"+result.toString());
				return result.toString();
			}

			Map<String, Object> redPacInv = pacInvs.get(0);

			int invetory = 0;

			try {
				invetory = Integer.parseInt(redPacInv.get("INVENTORY").toString());
			} catch (Exception e) {

			}

			if (invetory < 1) {
				result.put("isSuccess", "0");
				result.put("errorMsg", "红包库存不足" + stockNumberId);
				result.put("dealId", dealId);
				result.put("handleID", reqLogId);
				result.put("responseCode", "0007");
				log.info("[外部系统派发红包接口end]:"+result.toString());
				return result.toString();
			}

			depotCode = redPacInv.get("DEPOTCODE").toString();

		} catch (Exception e) {
			result.put("isSuccess", "0");
			result.put("errorMsg", "校验库存异常");
			result.put("responseCode", "1000");
			result.put("dealId", dealId);
			result.put("handleID", reqLogId);
			log.info("[外部系统派发红包接口end]:"+result.toString());
			return result.toString();
		}

		Map<String, Object> requestLog = null;

		try {
			dealId = paramJson.getString("dealId");
			if (dealId == null || "".equals(dealId.trim())) {
				result.put("isSuccess", "0");
				result.put("errorMsg", "交易号为空");
				result.put("dealId", dealId);
				result.put("handleID", reqLogId);
				result.put("responseCode", "0004");
				log.info("[外部系统派发红包接口end]:"+result.toString());
				return result.toString();
			}

			requestLog = this.constructRequestLog(celephoneNo, dealId, platformId, stockNumberId, depotCode);
			if ("1".equals(requestLog.get("isExist"))) {
				result.put("isSuccess", "0");
				result.put("errorMsg", "重复的交易号  "+requestLog.get("errormessage"));
				result.put("dealId", dealId);
				result.put("handleID", reqLogId);
				result.put("responseCode", "0002");
				log.info("[外部系统派发红包接口end]:"+result.toString());
				return result.toString();
			}
		} catch (Exception e) {
			result.put("isSuccess", "0");
			result.put("errorMsg", "校验交易号异常");
			result.put("responseCode", "1000");
			result.put("dealId", dealId);
			result.put("handleID", reqLogId);
			log.info("[外部系统派发红包接口end]:"+result.toString());
			return result.toString();
		}
		
		
		
		
		try {

			String url = "";

			try {

				// String url = "http://211.160.73.226//coupon/distribute";测试环境
				// String url = "https://wallet.95598pay.com";//正式环境
				url = this.ecbpRedPacInvMapper.getParaValue("95598pay.redpackets.extassign");
				if (url == null || "".equals(url.trim())) {
					result.put("isSuccess", "0");
					result.put("errorMsg", "URL为空");
					throw new RuntimeException("URL为空");
				}
			} catch (Exception e) {

				throw new RuntimeException("获取电e宝派发接口URL异常");
			}
			
			

			//调用电e宝接口，派发红包
			JSONObject responseJsonResult = null;
			try {
				Map<String, Object> reportMap = this.requestLogtoReportMap(requestLog);
				String responseResult = new HttpsClientTools().doHttpsPost(url, JSON.toJSONString(reportMap));
				log.info("红包派发响应结果原文" + responseResult);
				responseJsonResult = JSON.parseObject(responseResult);
				log.info("红包派发响应结果" + responseResult);
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException("派发红包异常" + e.getMessage());
			}

			
			log.info("更新日志开始");
			String respCode = this.updateEcBpRedPacReqLogMapperAfterResponse(responseJsonResult, requestLog);
			log.info("更新日志成功");
			
			
			log.info(respCode);
			if ("MAC00000".equals(respCode)) {

				
				log.info("派发成功");
				try {
					Map<String, Object> minusRedPacInv = new HashMap<String, Object>();
					Map<String, Object> redPacket = new HashMap<String, Object>();
					minusRedPacInv.put("id", stockNumberId);
					BpRedPacInv redPacInv = this.ecbpRedPacInvMapper.selectById(minusRedPacInv);
					if(redPacInv!=null&&redPacInv.getId()!=null){
						log.info("红包编号：============"+redPacInv.getId());
						redPacket.put("id", redPacInv.getId());
						redPacket.put("platformId", platformId);
						Integer count = this.bpBuyRedPacketMapper.updatePlatform(redPacket);
						
						log.info("更新库存数量成功"+count);
					}
					
					
				} catch (Exception e) {
					requestLog.put("assagn_status", "3");//
					log.info("红包派发成功, 消减库存失败");
				}
				
				result.put("isSuccess", "1");
				result.put("responseCode", "0000");


			} else {

				log.info("派发失败");
				result.put("isSuccess", "0");
				result.put("errorMsg", responseJsonResult.getJSONObject("data").getJSONObject("body").getString("errorMessage"));
				result.put("responseCode", "0008");
				
				log.info("派发失败" + responseJsonResult.getJSONObject("data").getJSONObject("body").getString("errorMessage"));
			}
			
			
			

		} catch (Exception e) {
			result.put("isSuccess", "0");
			result.put("errorMsg", e.getMessage());
			result.put("responseCode", "1000");
			
			requestLog.put("errormessage",  e.getMessage());
			
			log.info("派发失败" + e.getMessage());
			
			
		} finally {
			ecBpRedPacReqLogMapper.insertEcBpRedPacReqLogMapper(requestLog);
			reqLogId = Integer.parseInt(requestLog.get("id").toString());
			result.put("dealId", dealId);
			result.put("handleID", reqLogId);
		}
		log.info("[外部系统派发红包接口end]:"+result.toString());
		return result.toString();
	}
	
	/**
	 * 
	 * @param celephoneNo 外部系统传入的电话号码
	 * @param dealId   外部系统传入的交易号
	 * @param platformId 外部系统传入的平台编号
	 * @param stockNumberId 外部系统传过来的商城红包库存编号
	 * @param depotCode  电e宝红包库存编号
	 * @return
	 */
	private Map<String, Object> constructRequestLog(String celephoneNo, String dealId, String platformId,
			String stockNumberId, String depotCode) {

		log.info("外部系统传入的电话号码=============="+celephoneNo);
		log.info("外部系统传入的交易号==============="+dealId);
		log.info("外部系统传入的平台编号=============="+platformId);
		log.info("外部系统传过来的商城红包库存编号========"+stockNumberId);
		log.info("电e宝红包库存编号================="+depotCode);
		Map<String, Object> reqLog = new HashMap<String, Object>();
		reqLog.put("ext_sys_id", platformId);
		reqLog.put("ext_sys_order_id", dealId);

		List<Map<String, Object>> logs = this.ecBpRedPacReqLogMapper.queryEcBpRedPacReqLogMapper(reqLog);
		if (logs == null || logs.isEmpty()) {
			Map<String, Object> requestLog = new HashMap<String, Object>();
			// requestLog.put("id", "");
			requestLog.put("ext_sys_id", platformId);
			requestLog.put("ext_sys_order_id", dealId);
			requestLog.put("mall_red_pac_inv_id", stockNumberId);
			requestLog.put("request_time", new Timestamp(new Date().getTime()));//外部系统请求发送请求时间

			requestLog.put("batch_id", UUIDUtil.getUUID());//生成UUID
			requestLog.put("distflag", "2");//手机号派发
			requestLog.put("totalcount", "1");//派发红包个数固定为一
			requestLog.put("distributetime", new Timestamp(new Date().getTime()));
			requestLog.put("mobilephone", celephoneNo);

			requestLog.put("depotcode", depotCode);
			requestLog.put("couponcode", UUIDUtil.getUUID());//生成UUID
			requestLog.put("assagn_status", "0");//未派发

			return requestLog;
		} else {
			reqLog = logs.get(0);
			reqLog.put("isExist", "1");
		}

		return reqLog;

	}

	
	/**
	 * 根据请求日志构造电e宝派发接口报文
	 * 
	 * @param requestLog  请求日志
	 * @return
	 */
	private Map<String, Object> requestLogtoReportMap(Map<String, Object> requestLog) {

		Map<String, Object> headerMap = new HashMap<String, Object>();
		Map<String, Object> bodyMap = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> reportMap = new HashMap<String, Object>();

		String accessNo = this.ecbpRedPacInvMapper.getParaValue("integral.buyred.accessno");//"1000000001";//电e宝分配给商城的接入号
		String userId = this.ecbpRedPacInvMapper.getParaValue("integral.buyred.userid");//"2000001324";//电e宝分配给商城的用户编号

		dataMap.put("header", headerMap);
		dataMap.put("body", bodyMap);
		reportMap.put("data", dataMap);

		headerMap.put("userId", userId);
		headerMap.put("accessNo", accessNo);// 电e宝分配给商城的接入号

		Date distributeTime = (Date) requestLog.get("distributetime");
		SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDDHHmmss");

		bodyMap.put("batchID", requestLog.get("batch_id"));
		bodyMap.put("distributeTime", sdf.format(distributeTime));
		bodyMap.put("remark", "");
		bodyMap.put("totalCount", requestLog.get("totalcount"));
		bodyMap.put("distFlag", requestLog.get("distflag"));
		bodyMap.put("batchID", requestLog.get("batch_id"));

		List<Map<String, Object>> details = new ArrayList<Map<String, Object>>();
		Map<String, Object> detailMap = new HashMap<String, Object>();
		details.add(detailMap);
		detailMap.put("couponCode", requestLog.get("couponcode"));
		detailMap.put("depotCode", requestLog.get("depotcode"));
		detailMap.put("mobilePhone", requestLog.get("mobilephone"));
		detailMap.put("powerUserId", "");
		bodyMap.put("detail", details);

		String signData = "";
		String signDataDtl = accessNo + "|" + userId + "|" + requestLog.get("batch_id") + "|"
				+ requestLog.get("distflag") + "|" + requestLog.get("totalcount") + "|" + sdf.format(distributeTime)
				+ "|" + requestLog.get("mobilephone") + "|" + "" + "|" + requestLog.get("depotcode") + "|"
				+ requestLog.get("couponcode");
		htjcSignToolManageK.init();
		signData = htjcSignToolManageK.sign(signDataDtl);//生成签名
		log.info("=================signData【"+signData+"】=================");
		bodyMap.put("signData", signData);

		return reportMap;
	}
	
	
	/**
	 *  调用电e宝派发红包接口后 根据电e宝接口返回数据 更新请求日志
	 * 
	 * @param result  电e宝派发接口返回json对象
	 * @param requestLog 商城生成的请求日志
	 * @return  返回电e宝的响应吗
	 * @throws ParseException
	 */
	private String updateEcBpRedPacReqLogMapperAfterResponse(JSONObject result, Map<String, Object> requestLog) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		Timestamp dealTime = new Timestamp(sdf.parse(result.getJSONObject("data").getJSONObject("body").getString("dealTime")).getTime());
		String dealstatus = result.getJSONObject("data").getJSONObject("body").getString("dealStatus");
		String errormessage = result.getJSONObject("data").getJSONObject("body").getString("errorMessage");
		String assagn_status = "";

		String respCode = result.getJSONObject("data").getJSONObject("header").getString("respCode");
		if ("MAC00000".equals(respCode)) {
			assagn_status = "1";
		} else {

			assagn_status = "2";
		}

		requestLog.put("dealtime", dealTime);
		requestLog.put("dealstatus", dealstatus);
		requestLog.put("errormessage", errormessage);
		requestLog.put("assagn_status", assagn_status);
		requestLog.put("respcode", result.getJSONObject("data").getJSONObject("header").getString("respCode"));


		return respCode;
	}

	

}
